package com.wgo.precise.client.ui.view.projecttree;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerDropAdapter;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TransferData;

import com.wgo.precise.client.ui.controller.ModelStatus;
import com.wgo.precise.client.ui.controller.RequirementPlugin;
import com.wgo.precise.client.ui.model.facade.DNDTarget;
import com.wgo.precise.client.ui.model.facade.IModelPersistable;
import com.wgo.precise.client.ui.model.facade.INodeChild;
import com.wgo.precise.client.ui.model.facade.INodeParent;
import com.wgo.precise.client.ui.model.facade.IPropertiesContainer;
import com.wgo.precise.client.ui.view.util.ModelByteArrayTransfer;


/**
 * 
 * @author Petter L. H. Eide
 * @version $Id: ProjectTreePartDropAdapter.java,v 1.2 2006-02-19 16:29:37 petterei Exp $
 *
 */
public class ProjectTreePartDropAdapter extends ViewerDropAdapter implements DropTargetListener {

	private IModelPersistable target;

	public ProjectTreePartDropAdapter(Viewer viewer) {
		super(viewer);
	}

	/**
	 * @see org.eclipse.jface.viewers.ViewerDropAdapter#performDrop(java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean performDrop(Object data) {
		Object object = data;
		if (object instanceof IModelPersistable) {
			try {
				((INodeChild)object).setParent((INodeParent)target);
				RequirementPlugin.getInstance().getPreciseSubject().notifyModelChanged(null); //TODO modelChange
			} catch (Exception e) {
				RequirementPlugin.log(e, "DND failed..");
				return false;
			}
			return true;
		}
		return false;
	}

	/**
	 * @see org.eclipse.jface.viewers.ViewerDropAdapter#validateDrop(java.lang.Object, int, org.eclipse.swt.dnd.TransferData)
	 */
	@Override
	public boolean validateDrop(@SuppressWarnings("hiding") Object target, @SuppressWarnings("unused") int operation, TransferData transferType) 
	{ //TODO: why not use target?
		boolean validateOk = false;
		try {
			IPropertiesContainer source = (IPropertiesContainer)((StructuredSelection)((StructuredViewer)getViewer()).getSelection()).getFirstElement();
			if (
					target instanceof IModelPersistable
					&& getCurrentLocation() == LOCATION_ON
					&& ModelByteArrayTransfer.getInstance().isSupportedType(transferType) 
					&& target instanceof DNDTarget 
					&& ((DNDTarget)target).validTransfer(source)
			) {
				this.target = (IModelPersistable) target ;
				validateOk = true;
			}
		} catch (Throwable t) {
			RequirementPlugin.log(new ModelStatus(IStatus.ERROR, "Could not validate DND-target.", t));
		}
		return validateOk;
	}

}